package priv.chenkai.spring_cli.controller;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import priv.chenkai.spring_cli.client.bo.FileBo;
import priv.chenkai.spring_cli.service.FileUploadService;
import priv.chenkai.spring_cli.util.Result;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @Author:chenkai
 * @Date: 2018/5/11 9:51
 */
@RestController
public class FileUploadController {
    @Autowired
    private FileUploadService fileUploadService;

    /**
     * 上传单张图片
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value="/api/files/upload")
    public Result fileUpload(MultipartFile file,
                              HttpServletRequest request)throws Exception{
        //获得物理路径webapp所在路径
        String rootPath = "";
        String path="";
        if(!file.isEmpty()){
            //保存图片
            byte[] bytes = file.getBytes();
            String contentType = file.getContentType();
            path = fileUploadService.upload(bytes,contentType,rootPath);
        }
        System.out.println(path);
        request.setAttribute("imagesPath", path);
        return Result.successResult(path);
    }

    /**
     * 批量上传图片
     * @param file
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping(value="/api/files/uploads")
    public Result fileUpload(@RequestParam(value="file",required=false) MultipartFile[] file,
                              HttpServletRequest request)throws Exception{
        //获得物理路径webapp所在路径
        String rootPath = "";
        List<FileBo> files = Lists.newArrayList();
        for (MultipartFile mf : file) {
            FileBo bo = new FileBo(mf.getBytes(),mf.getContentType());
            files.add(bo);
        }
        //保存数据
        List<String> list = fileUploadService.uploads(files, rootPath);
        return Result.successResult(list);
    }
}
